<?php

namespace api\modules\v1_clinic\controllers;

use services\api\TreatmentRoomService;
use Yii;
use common\models\base\Project;
use services\member\MemberService;
use api\controllers\OnAuthController;
use yii\base\Exception;
use common\helpers\CommonHelper;
use services\api\JwtService;
use api\modules\v1_clinic\forms\LoginForm;

/**
 * 登录接口
 *
 * Class SiteController
 * @package api\modules\v1_clinic\controllers
 */
class SiteController extends OnAuthController
{
    public $modelClass = '';

    protected $optional = ['login', 'refresh', 'get-project-list', 'member-permission'];

    public $enableCsrfValidation = false;

    /**
     * @api {post} /v1_clinic/site/login 用户登录
     * @apiName login
     * @apiGroup Site
     *
     * @apiDescription 登录完成调用/v1_clinic/member/permissions,获取用户权限信息
     *
     * @apiParam {String} mobile                    手机号
     * @apiParam {String} password                  密码
     *
     * @apiSuccess {String} code                    状态码
     * @apiSuccess {String} message                 提示信息
     * @apiSuccess {Object} data                    返回内容
     * @apiSuccess {String} data.access_token       token令牌
     * @apiSuccess {Object} data.info               用户信息
     * @apiSuccess {Number} data.info.member_id     用户ID
     * @apiSuccess {String} data.info.username      用户名
     * @apiSuccess {String} data.info.realname      真实姓名
     * @apiSuccess {String} data.info.email         邮箱
     * @apiSuccess {String} data.info.mobile        手机号
     * @apiSuccess {Number} data.info.is_super      是否超管【1是、0否】
     * @apiSuccess {Number} data.info.project_id    默认项目ID
     *
     */
    public function actionLogin()
    {
        $params = Yii::$app->request->post();
        $params['username'] = $params['mobile'] ?? '';
        $model = new LoginForm();
        $model->attributes = $params;

        if ($model->validate()) {
            $member = $model->getUser();

            // 判断是否有权限
            $res = TreatmentRoomService::getMemberPermission($member['id'], $member['is_super'], $params['project_id']);

            if (!$res) {
                return CommonHelper::api(422, '权限不足，请联系管理员开通');
            }

            $token = JwtService::createJwt(['id' => $member['id'], 'username' => $member['username'], 'realname' => $member['realname'], 'is_super' => $member['is_super']]);
            return $this->asJson([
                'access_token' => $token,
                'info' => [
                    'member_id' => $member['id'],
                    'username' => $member['username'],
                    'realname' => $member['realname'],
                    'mobile' => $member['mobile'],
                    'is_super' => $member['is_super'],
                ]
            ]);
        }

        // 返回数据验证失败
        return CommonHelper::api(422, $this->getError($model));
    }

    /**
     * 未登录时获取项目（医院）列表
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionGetProjectList()
    {
        return Project::find()
            ->select('id, name, name_sx')
            ->where(['status' => Project::STATUS_ENABLE])
            ->asArray()
            ->all();
    }
}
